package com.sunchangpeng.wechat.core.http;

import com.sunchangpeng.wechat.core.exception.WechatClientException;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;

public class HttpResponseWrapper {
    private static final byte[] EMPTY_CONTENT = new byte[0];

    private final Response response;

    public static HttpResponseWrapper of(Response response) {
        return new HttpResponseWrapper(response);
    }

    private HttpResponseWrapper(Response response) {
        this.response = response;
    }

    public boolean isSuccessful() {
        return response.isSuccessful();
    }

    public String header(String name) {
        return response.header(name);
    }

    public MediaType contentType() {
        ResponseBody body = this.response.body();
        return body != null ? body.contentType() : null;
    }

    public String getBodyText() {
        ResponseBody body = body();
        try {
            return body != null ? body.string() : "";
        } catch (IOException e) {
            throw new WechatClientException("I/O error on " + response, e);
        }
    }

    public byte[] getBodyBytes() {
        ResponseBody body = body();
        try {
            return body != null ? body.bytes() : EMPTY_CONTENT;
        } catch (IOException e) {
            throw new WechatClientException("I/O error on " + response, e);
        }
    }

    private ResponseBody body() {
        if (!response.isSuccessful()) {
            throw new WechatClientException(response.toString());
        }
        return this.response.body();
    }
}
